// utils/taskManager.js
// 任务管理器 - 业务逻辑层

import { TaskStorage, Storage } from './storage.js'
import { createTaskTemplate, validateTask, formatTime, PRIORITY_MAP, TASK_STATUS, STORAGE_KEYS } from './constants.js'
import { ErrorHandler, FeedbackManager, StorageErrorHandler, ERROR_TYPES, ERROR_LEVELS } from './errorHandler.js'

/**
 * 任务管理器类
 */
class TaskManager {
  /**
   * 创建新任务
   * @param {string} title - 任务标题
   * @param {string} note - 任务备注
   * @param {number} priority - 优先级
   * @returns {Object} 操作结果
   */
  static createTask(title, note = '', priority = 2) {
    try {
      // 创建任务对象
      const task = createTaskTemplate(title, note, priority)
      
      // 验证任务数据
      const validation = validateTask(task)
      if (!validation.isValid) {
        return {
          success: false,
          message: validation.errors.join(', '),
          data: null
        }
      }

      // 保存任务
      const success = TaskStorage.addTask(task)
      
      if (success) {
        console.log('任务创建成功:', task)
        return {
          success: true,
          message: '任务创建成功',
          data: task
        }
      } else {
        return {
          success: false,
          message: '任务保存失败',
          data: null
        }
      }
    } catch (error) {
      console.error('创建任务失败:', error)
      ErrorHandler.handleError(error, ERROR_TYPES.STORAGE, ERROR_LEVELS.ERROR, {
        operation: 'createTask',
        title,
        priority
      })
      return {
        success: false,
        message: '创建任务时发生错误',
        data: null
      }
    }
  }

  /**
   * 获取任务列表
   * @param {Object} options - 选项
   * @param {string} options.filter - 筛选条件 ('all', 'pending', 'completed')
   * @param {string} options.priority - 优先级筛选 ('all', 'high', 'medium', 'low')
   * @param {string} options.sortBy - 排序字段
   * @param {string} options.order - 排序顺序
   * @returns {Array} 任务列表
   */
  static getTasks(options = {}) {
    try {
      const {
        filter = 'pending',
        priority = 'all',
        sortBy = 'createTime',
        order = 'desc'
      } = options

      let tasks = []

      // 根据状态筛选
      switch (filter) {
        case 'all':
          tasks = TaskStorage.getActiveTasks()
          break
        case 'pending':
          tasks = TaskStorage.getPendingTasks()
          break
        case 'completed':
          tasks = TaskStorage.getCompletedTasks()
          break
        default:
          tasks = TaskStorage.getPendingTasks()
      }

      // 根据优先级筛选
      if (priority !== 'all') {
        tasks = TaskStorage.filterTasksByPriority(tasks, priority)
      }

      // 排序
      tasks = TaskStorage.sortTasks(tasks, sortBy, order)

      // 格式化时间显示
      tasks = tasks.map(task => ({
        ...task,
        formattedTime: formatTime(task.createTime),
        priorityInfo: PRIORITY_MAP[task.priority]
      }))

      return tasks
    } catch (error) {
      console.error('获取任务列表失败:', error)
      return []
    }
  }

  /**
   * 获取所有任务
   * @param {boolean} includeDeleted - 是否包含已删除任务
   * @returns {Array} 任务数组
   */
  static getAllTasks(includeDeleted = false) {
    try {
      return TaskStorage.getAllTasks(includeDeleted)
    } catch (error) {
      console.error('获取所有任务失败:', error)
      return []
    }
  }

  /**
   * 获取单个任务
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  static getTaskById(taskId) {
    try {
      const tasks = this.getAllTasks()
      const task = tasks.find(t => t.id === taskId)
      
      if (!task) {
        return {
          success: false,
          message: '任务不存在',
          data: null
        }
      }

      // 添加格式化时间和优先级信息
      const formattedTask = {
        ...task,
        formattedTime: formatTime(task.createTime),
        formattedUpdateTime: formatTime(task.updateTime),
        priorityInfo: PRIORITY_MAP[task.priority]
      }
      
      if (task.completeTime) {
        formattedTask.formattedCompleteTime = formatTime(task.completeTime)
      }

      return {
        success: true,
        message: '获取任务成功',
        data: formattedTask
      }
    } catch (error) {
      console.error('获取任务失败:', error)
      return {
        success: false,
        message: '获取任务失败',
        data: null
      }
    }
  }

  /**
   * 更新任务
   * @param {string} taskId - 任务ID
   * @param {Object} updates - 更新的字段
   * @returns {Object} 操作结果
   */
  static updateTask(taskId, updates) {
    try {
      // 获取原任务
      const originalTask = TaskStorage.getTaskById(taskId)
      if (!originalTask) {
        return {
          success: false,
          message: '任务不存在',
          data: null
        }
      }

      // 合并更新数据
      const updatedTask = { ...originalTask, ...updates }
      
      // 验证更新后的任务数据
      const validation = validateTask(updatedTask)
      if (!validation.isValid) {
        return {
          success: false,
          message: validation.errors.join(', '),
          data: null
        }
      }

      // 更新任务
      const success = TaskStorage.updateTask(taskId, updates)
      
      if (success) {
        console.log('任务更新成功:', taskId)
        return {
          success: true,
          message: '任务更新成功',
          data: TaskStorage.getTaskById(taskId)
        }
      } else {
        return {
          success: false,
          message: '任务更新失败',
          data: null
        }
      }
    } catch (error) {
      console.error('更新任务失败:', error)
      return {
        success: false,
        message: '更新任务时发生错误',
        data: null
      }
    }
  }

  /**
   * 完成任务
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  static completeTask(taskId) {
    try {
      const success = TaskStorage.completeTask(taskId)
      
      if (success) {
        console.log('任务完成:', taskId)
        return {
          success: true,
          message: '任务已完成',
          data: TaskStorage.getTaskById(taskId)
        }
      } else {
        return {
          success: false,
          message: '完成任务失败',
          data: null
        }
      }
    } catch (error) {
      console.error('完成任务失败:', error)
      return {
        success: false,
        message: '完成任务时发生错误',
        data: null
      }
    }
  }

  /**
   * 恢复任务为待完成状态
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  static uncompleteTask(taskId) {
    try {
      const tasks = this.getAllTasks()
      const taskIndex = tasks.findIndex(task => task.id === taskId)
      
      if (taskIndex === -1) {
        return {
          success: false,
          message: '任务不存在'
        }
      }
      
      const task = tasks[taskIndex]
      
      if (task.status !== TASK_STATUS.COMPLETED) {
        return {
          success: false,
          message: '任务未完成，无需恢复'
        }
      }
      
      // 更新任务状态
      task.status = TASK_STATUS.PENDING
      task.updateTime = Date.now()
      task.completeTime = null
      
      // 保存到本地存储
      TaskStorage.saveTasks(tasks)
      
      return {
        success: true,
        message: '任务已恢复为待完成',
        data: task
      }
    } catch (error) {
      console.error('恢复任务失败:', error)
      return {
        success: false,
        message: '恢复任务失败'
      }
    }
  }

  /**
   * 删除任务
   * @param {string} taskId - 任务ID
   * @returns {Object} 操作结果
   */
  static deleteTask(taskId) {
    try {
      const success = TaskStorage.deleteTask(taskId)
      
      if (success) {
        console.log('任务删除:', taskId)
        return {
          success: true,
          message: '任务已删除',
          data: null
        }
      } else {
        return {
          success: false,
          message: '删除任务失败',
          data: null
        }
      }
    } catch (error) {
      console.error('删除任务失败:', error)
      return {
        success: false,
        message: '删除任务时发生错误',
        data: null
      }
    }
  }

  /**
   * 获取任务统计信息
   * @returns {Object} 统计信息
   */
  static getTaskStats() {
    try {
      const stats = TaskStorage.getTaskStats()
      
      return {
        ...stats,
        highPriorityCount: TaskStorage.filterTasksByPriority(TaskStorage.getPendingTasks(), 'high').length,
        mediumPriorityCount: TaskStorage.filterTasksByPriority(TaskStorage.getPendingTasks(), 'medium').length,
        lowPriorityCount: TaskStorage.filterTasksByPriority(TaskStorage.getPendingTasks(), 'low').length
      }
    } catch (error) {
      console.error('获取统计信息失败:', error)
      return {
        total: 0,
        pending: 0,
        completed: 0,
        completionRate: 0,
        highPriorityCount: 0,
        mediumPriorityCount: 0,
        lowPriorityCount: 0
      }
    }
  }

  /**
   * 批量操作任务
   * @param {Array} taskIds - 任务ID数组
   * @param {string} operation - 操作类型：'complete', 'delete', 'restore'
   * @returns {Object} 操作结果
   */
  static batchOperation(taskIds, operation) {
    try {
      if (!Array.isArray(taskIds) || taskIds.length === 0) {
        return {
          success: false,
          message: '请选择要操作的任务'
        }
      }
      
      const tasks = this.getAllTasks()
      let successCount = 0
      let failCount = 0
      
      taskIds.forEach(taskId => {
        const taskIndex = tasks.findIndex(task => task.id === taskId)
        
        if (taskIndex === -1) {
          failCount++
          return
        }
        
        const task = tasks[taskIndex]
        
        switch (operation) {
          case 'complete':
            if (task.status === TASK_STATUS.PENDING) {
              task.status = TASK_STATUS.COMPLETED
              task.updateTime = Date.now()
              task.completeTime = Date.now()
              successCount++
            } else {
              failCount++
            }
            break
            
          case 'delete':
            if (task.status !== TASK_STATUS.DELETED) {
              task.status = TASK_STATUS.DELETED
              task.updateTime = Date.now()
              task.isDeleted = true
              successCount++
            } else {
              failCount++
            }
            break
            
          case 'restore':
            if (task.status === TASK_STATUS.COMPLETED) {
              task.status = TASK_STATUS.PENDING
              task.updateTime = Date.now()
              task.completeTime = null
              successCount++
            } else {
              failCount++
            }
            break
            
          default:
            failCount++
        }
      })
      
      // 保存到本地存储
      TaskStorage.saveTasks(tasks)
      
      // 生成结果消息
      let message = ''
      if (successCount > 0) {
        const operationText = {
          'complete': '完成',
          'delete': '删除',
          'restore': '恢复'
        }[operation] || '操作'
        
        message = `成功${operationText}了 ${successCount} 个任务`
        if (failCount > 0) {
          message += `，${failCount} 个任务操作失败`
        }
      } else {
        message = '批量操作失败'
      }
      
      return {
        success: successCount > 0,
        message: message,
        data: {
          successCount,
          failCount,
          totalCount: taskIds.length
        }
      }
    } catch (error) {
      console.error('批量操作失败:', error)
      return {
        success: false,
        message: '批量操作失败'
      }
    }
  }

  /**
   * 清空所有任务
   * @returns {Object} 操作结果
   */
  static clearAllTasks() {
    try {
      const success = TaskStorage.clearAllTasks()
      
      if (success) {
        console.log('所有任务已清空')
        return {
          success: true,
          message: '所有任务已清空',
          data: null
        }
      } else {
        return {
          success: false,
          message: '清空任务失败',
          data: null
        }
      }
    } catch (error) {
      console.error('清空任务失败:', error)
      return {
        success: false,
        message: '清空任务时发生错误',
        data: null
      }
    }
  }

  /**
   * 初始化示例数据
   * @returns {Object} 操作结果
   */
  static initSampleData() {
    try {
      // 检查是否已有数据
      const existingTasks = TaskStorage.getAllTasks()
      if (existingTasks.length > 0) {
        return {
          success: false,
          message: '已存在任务数据',
          data: null
        }
      }

      // 创建示例任务
      const sampleTasks = [
        createTaskTemplate('完成项目文档', '编写项目需求文档和技术文档', 1),
        createTaskTemplate('学习微信小程序开发', '掌握小程序基础开发技能', 2),
        createTaskTemplate('准备会议材料', '整理下周例会的汇报材料', 1),
        createTaskTemplate('健身计划', '每天坚持运动30分钟', 3),
        createTaskTemplate('读书笔记', '阅读《深入理解计算机系统》', 2)
      ]

      // 保存示例数据
      const success = TaskStorage.saveTasks(sampleTasks)
      
      if (success) {
        console.log('示例数据初始化成功')
        return {
          success: true,
          message: '示例数据初始化成功',
          data: sampleTasks
        }
      } else {
        return {
          success: false,
          message: '示例数据初始化失败',
          data: null
        }
      }
    } catch (error) {
      console.error('初始化示例数据失败:', error)
      return {
        success: false,
        message: '初始化示例数据时发生错误',
        data: null
      }
    }
  }

  /**
   * 导出所有数据
   * @returns {Object} 导出的数据
   */
  static exportAllData() {
    try {
      const tasks = this.getAllTasks()
      const stats = this.getTaskStats()
      
      const exportData = {
        version: '1.0.0',
        exportTime: new Date().toISOString(),
        totalTasks: tasks.length,
        data: {
          tasks: tasks,
          statistics: stats,
          settings: this.getSettings()
        }
      }
      
      return { success: true, data: exportData }
    } catch (error) {
      console.error('导出数据失败:', error)
      return { success: false, message: '导出数据失败' }
    }
  }

  /**
   * 获取应用设置
   * @returns {Object} 应用设置
   */
  static getSettings() {
    try {
      return Storage.getItem('todolist_settings') || {
        theme: 'default',
        notifications: true,
        autoBackup: false,
        language: 'zh-CN'
      }
    } catch (error) {
      console.error('获取设置失败:', error)
      return {}
    }
  }

  /**
   * 保存应用设置
   * @param {Object} settings 设置对象
   * @returns {Object} 保存结果
   */
  static saveSettings(settings) {
    try {
      const currentSettings = this.getSettings()
      const updatedSettings = { ...currentSettings, ...settings }
      
      Storage.setItem('todolist_settings', updatedSettings)
      return { success: true, message: '设置保存成功' }
    } catch (error) {
      console.error('保存设置失败:', error)
      return { success: false, message: '保存设置失败' }
    }
  }

  /**
   * 获取数据统计报告
   * @returns {Object} 统计报告
   */
  static getAnalyticsReport() {
    try {
      const tasks = this.getAllTasks()
      const now = Date.now()
      
      // 时间范围
      const today = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      const thisWeek = now - 7 * 24 * 60 * 60 * 1000
      const thisMonth = now - 30 * 24 * 60 * 60 * 1000
      
      // 基础统计
      const totalTasks = tasks.length
      const completedTasks = tasks.filter(t => t.status === 1).length
      const pendingTasks = tasks.filter(t => t.status === 0).length
      
      // 时间段统计
      const todayCreated = tasks.filter(t => t.createTime >= today).length
      const weekCreated = tasks.filter(t => t.createTime >= thisWeek).length
      const monthCreated = tasks.filter(t => t.createTime >= thisMonth).length
      
      const weekCompleted = tasks.filter(t => t.status === 1 && t.completeTime >= thisWeek).length
      const monthCompleted = tasks.filter(t => t.status === 1 && t.completeTime >= thisMonth).length
      
      // 优先级统计
      const priorityStats = {
        high: tasks.filter(t => t.priority === 1).length,
        medium: tasks.filter(t => t.priority === 2).length,
        low: tasks.filter(t => t.priority === 3).length
      }
      
      // 完成率
      const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0
      
      // 平均完成时间（已完成任务的创建到完成时间）
      const completedTasksWithTime = tasks.filter(t => t.status === 1 && t.completeTime)
      const avgCompletionTime = completedTasksWithTime.length > 0 
        ? completedTasksWithTime.reduce((sum, task) => sum + (task.completeTime - task.createTime), 0) / completedTasksWithTime.length
        : 0
      
      return {
        success: true,
        data: {
          basic: {
            totalTasks,
            completedTasks,
            pendingTasks,
            completionRate
          },
          timeRange: {
            today: { created: todayCreated },
            week: { created: weekCreated, completed: weekCompleted },
            month: { created: monthCreated, completed: monthCompleted }
          },
          priority: priorityStats,
          performance: {
            avgCompletionTime: Math.round(avgCompletionTime / (1000 * 60 * 60)), // 转换为小时
            weeklyAverage: Math.round(weekCompleted / 7 * 10) / 10,
            monthlyAverage: Math.round(monthCompleted / 30 * 10) / 10
          }
        }
      }
    } catch (error) {
      console.error('获取统计报告失败:', error)
      return { success: false, message: '获取统计报告失败' }
    }
  }

  /**
   * 备份数据到本地
   * @returns {Object} 备份结果
   */
  static backupData() {
    try {
      const exportResult = this.exportAllData()
      if (!exportResult.success) {
        return exportResult
      }

      const backupKey = `todolist_backup_${Date.now()}`
      Storage.setItem(backupKey, exportResult.data)

      // 保存备份记录
      const backupList = this.getBackupList()
      backupList.push({
        key: backupKey,
        time: Date.now(),
        taskCount: exportResult.data.totalTasks
      })

      // 只保留最近10个备份
      if (backupList.length > 10) {
        const oldBackup = backupList.shift()
        Storage.removeItem(oldBackup.key)
      }

      Storage.setItem('todolist_backup_list', backupList)

      return { 
        success: true, 
        message: '数据备份成功',
        backupKey 
      }
    } catch (error) {
      console.error('备份数据失败:', error)
      return { success: false, message: '备份数据失败' }
    }
  }

  /**
   * 获取备份列表
   * @returns {Array} 备份列表
   */
  static getBackupList() {
    try {
      return Storage.getItem('todolist_backup_list') || []
    } catch (error) {
      console.error('获取备份列表失败:', error)
      return []
    }
  }
}

export { TaskManager } 